---------------------------------------------------------------
-- @Copyright：           wuwenkui
-- @Description：         服务器内部调用接口封装

-- @modify time           2021-07-29
---------------------------------------------------------------
require "modules.business_advert.advert_define"
local gg = require "modules.business_advert.advert_gg"
local advert_common = require "modules.business_advert.advert_common"
local process_api = require "modules.business_advert.advert_process_api"
local b_common     = require "modules.business_common.business_common"

local FOO = {
    _VERSION = '0.1.0',
}

--删除玩家广告信息
FOO.ad_del_position_info_business = function()
    --客户端传参校验
    if not tonumber(ngx.ctx.m_params.uin) 
    or not tonumber(ngx.ctx.m_params.apiid)
    or not ngx.ctx.m_params.position_id     --这个接口的position是 xx_xx可以带多个广告位，其余都是1个广告位
    or not tonumber(ngx.ctx.m_params.platform_id) then
        log.day_list(ADVERT, "[ERROR] (cmds: ad_del_position_info_business) ERROR_PARAM!  uin= "
            ..(tonumber(ngx.ctx.m_params.uin) or "nil") .." channel=".. (tonumber(ngx.ctx.m_params.apiid) or "nil")
            .." position="..(tonumber(ngx.ctx.m_params.position_id) or "nil").." platform="..(tonumber(ngx.ctx.m_params.platform_id) or "nil"))

        return gg.return_table(ERROR_CODE.OR_PARAM)
    end

    local uin = tonumber(ngx.ctx.m_params.uin)
    local channel = tonumber(ngx.ctx.m_params.apiid)
    local position_ids_param = ngx.ctx.m_params.position_id
    local platform_id = tonumber(ngx.ctx.m_params.platform_id)

    local platform_config = ns_config.advert_change_config.config.config_channel[channel][platform_id]
    if not platform_config then 
        log.day_list(ADVERT, "[ERROR]cmds: ad_del_position_info_business no platform_config! channel="..channel.." platform_id="..platform_id)
        return gg.return_table(ERROR_CODE.OR_ERROR_PLATFORM)
    end
    local position_t= {}
    for v in string.gmatch(position_ids_param, "(%d+)") do
        table.insert(position_t, (tonumber(v) or v ) )
    end
    if #position_t==0 then 
        log.day_list(ADVERT, "[ERROR]cmds: ad_del_position_info_business error position_ids_param="..position_ids_param)
        return gg.return_table(ERROR_CODE.OR_PARAM)
    end

    --del
    for _, position_id in pairs(position_t) do
        local ssdb_key_ad_info = process_api.calc_ssdb_hash_ad_info(channel, platform_id, position_id) 
        gg.private_hash_del_key(uin%10, uin, ssdb_key_ad_info)
    end

    gg.return_table(ERROR_CODE.OR_SUCCESS)
end

--后台更新推送通知： 仅在此处 写 ssdb的更新时间 
FOO.web_update_config = function()
    if not tonumber(ngx.ctx.m_params.type) then 
        log.day_list(ADVERT, "[ERROR] web_update_config type==nil!")
        --web更新传参错误了，就打印错误并主动去拉全部
        FOO.pull_web_config()
        return gg.return_table(ERROR_CODE.OR_WEB_NOTIFY_ERROR) 
    end

    local update_config_type = tonumber(ngx.ctx.m_params.type)
    if not WEB_CONFIG_NAME[update_config_type] then
        log.day_list(ADVERT, "[ERROR] web_update_config error type="..update_config_type)
        return gg.return_table(ERROR_CODE.OR_NOT_SUPPORT_TYPE) 
    end
    
    --更新配置
    local update_config_code = process_api.update_config_by_type(update_config_type)
    if update_config_code.ret~=ERROR_CODE.OR_SUCCESS.ret then 
        log.day_list(ADVERT, "[ERROR]cmds: web_update_config update_config_by_type error!")
        --再拉一次
        local again_update_code = process_api.update_config_by_type(update_config_type)
        if again_update_code.ret~=ERROR_CODE.OR_SUCCESS.ret then 
            log.day_list(ADVERT, "[ERROR]cmds: web_update_config update_config_by_type AGAIN error!")
            return gg.return_table(again_update_code)
        end
    end

    --更新后的缓存配置表正确性校验
    local check_config_code = process_api.check_config()
    if check_config_code.ret~=ERROR_CODE.OR_SUCCESS.ret then 
        --校验失败就用备份数据还原
        ns_config.advert_raw_config = ns_config.backup_config.advert_raw_config
        ns_config.advert_change_config = ns_config.backup_config.advert_change_config
        log.day_list(ADVERT, "[ERROR]cmds: web_update_config check_config fail!")
        return  gg.return_table(check_config_code)
    end

    --ssdb写最后更新时间
    local now_time = uu.now()
    local ret = gg.private_hash_set_table_ssdb(SSDB_COMM, 0, SSDB_KEY_DEF.UPDATE_CONFIG_TIME,
        { update_time = now_time }, _WRITE_SSDB_WITHOUT_LOCK_)
    if ret~="OK" then 
        log.day_list(ADVERT, "[ERROR]cmds: web_update_config private_hash_set_table_ssdb [ret NONE]")
        return gg.return_table(ERROR_CODE.OR_FAIL) 
    end
    --同步更新时间
    ns_config.update_time = now_time

    --本地缓存配置
    if ns_config.advert_change_config.config then 
        local set_ret = b_common.business_nginx_share.set_nginx_share(AD_SHARE, ns_config.dict_name.config_data, ns_config)
        if set_ret==false then 
            log.day_list(ADVERT, "[ERROR]web_update_config: set_nginx_share.config_data ERROR!")
        end
    end

    --本地缓存更新时间
    local set_time_ret = b_common.business_nginx_share.set_nginx_share(AD_SHARE, ns_config.dict_name.web_update_time, {ns_config.update_time})
    if set_time_ret==false then 
        log.day_list(ADVERT, "[ERROR]web_update_config: set_nginx_share.web_update_time ERROR!")
    end

    --日志记录
    log.day_list(ADVERT, "[INFO]cmds: web_update_config SUCCESS! type="..(ngx.ctx.m_params.type or "nil")
    .." | ts= "..now_time.." | date= "..advert_common.ts2date(now_time))
    --备份下通过检测校验的正确配置数据
    ns_config.backup_config.advert_raw_config = ns_config.advert_raw_config
    ns_config.backup_config.advert_change_config = ns_config.advert_change_config

    return gg.return_table(ERROR_CODE.OR_SUCCESS)
end

--主动拉取web配置
FOO.pull_web_config = function()
    --更新配置
    local update_code = process_api.update_all_config()
    if update_code.ret~=ERROR_CODE.OR_SUCCESS.ret then 
        log.day_list(ADVERT, "[ERROR] (pull_web_config) update_all_config error!")
        return gg.return_table(update_code)
    end

    --同步SSDB里记录的更新时间
    local body = gg.private_hash_get_table_ssdb(SSDB_COMM, 0, SSDB_KEY_DEF.UPDATE_CONFIG_TIME)
    if not body.update_time then 
        body.update_time  = uu.now()
        gg.private_hash_set_table_ssdb(SSDB_COMM, 0, SSDB_KEY_DEF.UPDATE_CONFIG_TIME, { update_time = body.update_time })
    end
    ns_config.update_time = body.update_time 

    --本地缓存配置
    if ns_config.advert_change_config.config then 
        local set_ret = b_common.business_nginx_share.set_nginx_share(AD_SHARE, ns_config.dict_name.config_data, ns_config)
        if set_ret==false then 
            log.day_list(ADVERT, "[ERROR]pull_web_config: set_nginx_share.config_data ERROR!")
        end
    end

    --本地缓存更新时间
    local set_time_ret = b_common.business_nginx_share.set_nginx_share(AD_SHARE, ns_config.dict_name.web_update_time, {ns_config.update_time})
    if set_time_ret==false then 
        log.day_list(ADVERT, "[ERROR]pull_web_config: set_nginx_share.web_update_time ERROR!")
    end

    --备份下通过检测校验的正确配置数据
    log.day_list(ADVERT, "[INFO]cmds: pull_web_config SUCCESS! ns_config.update_time="..ns_config.update_time) 
    ns_config.backup_config.advert_raw_config = ns_config.advert_raw_config
    ns_config.backup_config.advert_change_config = ns_config.advert_change_config

    return gg.return_table(ERROR_CODE.OR_SUCCESS)
end

--定时器事件[不要用gg.return(), 定时器里nginx.say会提示错误]
FOO.timer_work = function ()
    gg.init()

    --更新配置
    local update_code = process_api.update_all_config()
    if update_code.ret~=ERROR_CODE.OR_SUCCESS.ret then 
        log.day_list(ADVERT, "[ERROR] (timer_work) update_all_config error!")
        return update_code
    end
 
    --同步SSDB里记录的更新时间
    local body = gg.private_hash_get_table_ssdb(SSDB_COMM, 0, SSDB_KEY_DEF.UPDATE_CONFIG_TIME)
    if not body.update_time then 
        body.update_time = uu.now()
        gg.private_hash_set_table_ssdb(SSDB_COMM, 0, SSDB_KEY_DEF.UPDATE_CONFIG_TIME, { update_time = body.update_time })
    end
    ns_config.update_time = body.update_time

    --本地缓存配置
    if ns_config.advert_change_config.config then 
        local set_ret = b_common.business_nginx_share.set_nginx_share(AD_SHARE, ns_config.dict_name.config_data, ns_config)
        if set_ret==false then 
            log.day_list(ADVERT, "[ERROR]timer_work: set_nginx_share.config_data ERROR!")
        end
    end

    --本地缓存更新时间
    local set_time_ret = b_common.business_nginx_share.set_nginx_share(AD_SHARE, ns_config.dict_name.web_update_time, {ns_config.update_time})
    if set_time_ret==false then 
        log.day_list(ADVERT, "[ERROR]timer_work: set_nginx_share.web_update_time ERROR!")
    end

    --备份下通过检测校验的正确配置数据
    log.day_list(ADVERT, "[INFO]cmds: timer_work update SUCCESS! ns_config.update_time="..ns_config.update_time) 
    ns_config.backup_config.advert_raw_config = ns_config.advert_raw_config
    ns_config.backup_config.advert_change_config = ns_config.advert_change_config
    
    gg.final()

    return ERROR_CODE.OR_SUCCESS
end

--当玩家配置数据结构修改时，通过调用该函数更新时间戳[同理也可以去后台点击刷新配置] \
--复位所有玩家SSDB内的配置数据[玩家主动请求的同时复位]
FOO.reset_all_user_config = function ()
    --ssdb写最后更新时间
    local now_time = uu.now()
    local ret = gg.private_hash_set_table_ssdb(SSDB_COMM, 0, SSDB_KEY_DEF.UPDATE_CONFIG_TIME,
        { update_time = now_time }, _WRITE_SSDB_WITHOUT_LOCK_)
    if ret~="OK" then 
        log.day_list(ADVERT, "[ERROR]cmds: reset_all_user_config private_hash_set_table_ssdb [ret NONE]")
        return gg.return_table(ERROR_CODE.OR_FAIL) 
    end
    --同步更新时间
    ns_config.update_time = now_time
 
    --本地缓存配置
    if ns_config.advert_change_config.config then 
        local set_ret = b_common.business_nginx_share.set_nginx_share(AD_SHARE, ns_config.dict_name.config_data, ns_config)
        if set_ret==false then 
            log.day_list(ADVERT, "[ERROR]web_update_config: set_nginx_share.config_data ERROR!")
        end
    end

    --本地缓存更新时间
    local set_time_ret = b_common.business_nginx_share.set_nginx_share(AD_SHARE, ns_config.dict_name.web_update_time, {ns_config.update_time})
    if set_time_ret==false then 
        log.day_list(ADVERT, "[ERROR]timer_work: set_nginx_share.web_update_time ERROR!")
    end

    --日志记录
    log.day_list(ADVERT, "[INFO]cmds: reset_all_user_config SUCCESS! "
        .." | ts= "..now_time.." | date= "..advert_common.ts2date(now_time))

    return gg.return_table(ERROR_CODE.OR_SUCCESS)
end

--设置玩家数据
FOO.set_user_info = function ()
    local uin = tonumber(ngx.ctx.m_params.uin)
    local channel = tonumber(ngx.ctx.m_params.apiid or 1)
    local position_ids_param = ngx.ctx.m_params.position_id or 5
    local platform_id = tonumber(ngx.ctx.m_params.platform_id or 1018)
    local counts = tonumber(ngx.ctx.m_params.counts or 4)
    local is_position_max = ngx.ctx.m_params.is_position_max

    local position_t= {}
    for v in string.gmatch(position_ids_param, "(%d+)") do
        table.insert(position_t, (tonumber(v) or v ) )
    end
    if #position_t==0 then 
        log.day_list(ADVERT, "[ERROR]set_user_info error position_ids_param="..position_ids_param)
        return gg.return_table(ERROR_CODE.OR_PARAM)
    end
    local ret_position_infos = {}

    for _, position_id in pairs(position_t) do
        local ssdb_key_ad_info = process_api.calc_ssdb_hash_ad_info(channel, platform_id, position_id) 
        local user_config_info = gg.private_hash_get_table_ssdb(uin%10, uin, ssdb_key_ad_info)
        if user_config_info.config then 
            user_config_info.config.change_config.today.finish.count = counts
            user_config_info.config.change_config.today.start.count = counts
            if is_position_max then 
                user_config_info.config.change_config.today.is_position_max = tonumber(ngx.ctx.m_params.is_position_max)
            end

            local ret = gg.private_hash_set_table_ssdb(uin%10, uin, ssdb_key_ad_info, user_config_info) 
            if ret~="OK" then 
                log.day_list(ADVERT, "[WARNING] (cmds): set_user_info) \
                    private_hash_set_table_ssdb [ret NONE]")
            else
                --获取该广告位的具体信息
                ret_position_infos[position_id] = user_config_info.config.change_config.today
            end
        end
    end

    return gg.return_table(ERROR_CODE.OR_SUCCESS, ret_position_infos)
end

--内部测试专用接口
FOO.ad_test_cmd = function ()
    log.debug("=================================================ad_test_cmd=================================================")

    local channel_info = b_common.business_nginx_share.get_nginx_share(AD_SHARE, ns_config.dict_name.channel_info)
    uu.var_dump( (channel_info or "nil") )

    local uin = tonumber(ngx.ctx.m_params.uin)
    local channel = tonumber(ngx.ctx.m_params.apiid or 1)
    local position_id = tonumber(ngx.ctx.m_params.position_id) or 5
    local platform_id = tonumber(ngx.ctx.m_params.platform_id or 1018)

    --回写ssdb
    local ssdb_key_ad_info = process_api.calc_ssdb_hash_ad_info(channel, platform_id, position_id) 
    local user_config_info = gg.private_hash_get_table_ssdb(uin%10, uin, ssdb_key_ad_info)
    uu.var_dump( {[position_id]= user_config_info} )
    local data = {}
    if user_config_info.config then 
	    data.position_id = position_id
        data.finish_count = user_config_info.config.change_config.today.finish.count
    end
    
    uu.var_dump(ns_config)

    --user_config_info.config.change_config.today.finish.count = counts
    --gg.set_nginx_share(AD_SHARE, "test2", test_value)
    --[[
    log.debug("######################################")
    uu.var_dump(gg.get_nginx_share(AD_SHARE, "test2"))
    log.debug("######################################")
    gg.del_nginx_share(AD_SHARE, "test3")
    uu.var_dump(gg.get_keys_share(AD_SHARE, 100))
    log.debug("######################################")
    gg.flush_nginx_share(AD_SHARE)
    uu.var_dump(gg.get_keys_share(AD_SHARE, 100))
    log.debug("######################################")
    gg.del_nginx_share(AD_SHARE, "test2")
    uu.var_dump(gg.get_keys_share(AD_SHARE, 100))
    log.debug("######################################")
    gg.clear_nginx_share(AD_SHARE)
    uu.var_dump(gg.get_keys_share(AD_SHARE, 100))
    --]]

    --advert_common.log_debug( "gg.key= ", true)
    --advert_common.log_debug( "gg.key= ", 1212212)
    --advert_common.log_debug( "gg.key= ", "22323232")

    return gg.return_table(ERROR_CODE.OR_SUCCESS, data)
end



return FOO